import React, { Component, Fragment } from 'react'
import { connect } from 'react-redux'
import { HashRouter as Router, Switch, Route, Redirect, Link } from 'react-router-dom'
import Empty from 'component/empty'

import { getRouterData } from 'common/router'

const routerData = getRouterData()

export default function App () {
  const Login = routerData['/'].component
  const Home = routerData['/home'].component
  const HouseLayout = routerData['/house'].component
  const Pay = routerData['/pay'].component

  // 提前加载loading图片,因为图片太大啦

  return (
    <Fragment>
      <div style = { { backgroundImage: `url(${ require('asset/img/loading.png') })` } } />
      <Router>
        <Switch>
          <Route path = '/' component = { Login } exact />
          <Route path = '/home' component = { Home } exact />
          <AuthRoute path = '/house' component = { HouseLayout } auth = 'login' />
          <AuthRoute path = '/pay' component = { Pay } exact auth = 'login' />
          <Route component = { () => <Empty type = '404' text = { <span>没有这个页面 <Link to = '/'>返回首页</Link></span> } /> } />
        </Switch>
      </Router>
    </Fragment>
  )
}

@connect(state => ({
  user: state.user
}))
class AuthRoute extends Component {
  render () {
    const {
      user: {
        auth: authList
      },

      component: Component,
      auth,

      ...rest
    } = this.props

    return (
      <Route
        { ...rest }

        render = {
          props => {
            if (authList.indexOf(auth) < 0) {
              return <Redirect to = '/' />
            }

            return <Component { ...props } />
          }
        }
      />
    )
  }
}
